import { PageContainer } from '@ant-design/pro-layout';
import React, { useState, useRef, useEffect } from 'react';
import { request } from 'umi';
import { Modal, message, Tabs } from 'antd';
import ProCard from '@ant-design/pro-card';
import TaskList from './components/TaskList';
import TaskForm from './components/TaskForm';
import Dashboard from './components/Dashboard';
import OfflineImportModal from './components/OfflineImportModal';
import { getTask, offlineImport } from './service'
import { useIntl } from 'umi';
import _ from "lodash";


const { Divider } = ProCard;

const Diagnose = (props) => {
    const refTaskList = useRef([]);
    const [pannelConfig, setPannelConfig] = useState();
    const [data, setData] = useState();
    const [offlineImportModalVisible, setOfflineImportModalVisibles] = useState({
        ssh: false
    });
    const setOfflineImportModalVisible = (channel, visible) => {
        setOfflineImportModalVisibles({
            ...offlineImportModalVisible,
            [channel]: visible
        })
    };
    const [offlineImportLoading, setOfflineImportLoadings] = useState({
        ssh: false
    });
    const setOfflineImportLoading = (channel, loading) => {
        setOfflineImportLoadings({
            ...offlineImportLoading,
            [channel]: loading
        })
    };
    const [multichannelConfig, setMultichannelConfig] = useState([
        {
            "name": "ssh",
            "label": "SSH通道",
            "extra_params": {
                "*": []
            }
        }
    ])
    const [currentTab, setCurrentTab] = useState('ssh');
    const intl = useIntl();

    useEffect(() => {
        request("/resource/diagnose/v2/multichannel.json")
            .catch(err => {
                return Promise.resolve({
                    "version": 1.0,
                    "channels": [
                        {
                            "name": "ssh",
                            "label": "SSH通道",
                            "extra_params": {
                                "*": []
                            }
                        }
                    ]
                })
            })
            .then(res => {
                // Multichannel
                setMultichannelConfig(res["channels"])
                setCurrentTab(res.channels[0].name)

                // Get config
                let urlslice = props.match.url.split("/")
                urlslice.splice(2, 0, "v2")
                return request(`/resource${urlslice.join("/")}.json`)
            })
            .then((res) => {
                setPannelConfig(res)
            })


    }, []);

    const onError = async (record) => {
        // window.open(`/diagnose/detail/${record.task_id}`)
        const msg = await getTask(record.task_id);
        Modal.error({
            title: '诊断失败',
            content: (
                <div>
                    <div>错误信息: {msg?.err_msg ? msg.err_msg : msg?.result}</div>
                </div>
            ),
        });
    }

    const refreshTask = async (record) => {
        const msg = await getTask(record.task_id);

        // window.open(`/diagnose/detail/${record.task_id}`)

        setData({ ...msg, ...msg.result });

    }

    let multiChannelTaskforms = multichannelConfig.map(item => {
        return {
            label: item.label,
            key: item.name,
            forceRender: true,
            children: (
                <div>
                    {pannelConfig && <>
                        <TaskForm
                            taskForm={item.extra_params["*"].concat(pannelConfig.taskform)}
                            serviceName={pannelConfig.servicename}
                            queryParams={props?.location?.query}
                            onSuccess={() => {
                                console.log("try reload", refTaskList)
                                refTaskList.current[item.name].reload();
                                // refTaskList.current.reload();
                            }}
                            onOfflineLoad={() => {
                                setOfflineImportModalVisible(item.name, true);
                            }}
                        />

                        <Divider />
                        <TaskList serviceName={pannelConfig.servicename} channel={!!item.name ? item.name : "ssh"}
                            onClick={refreshTask}
                            onError={onError} ref={(el) => (refTaskList.current[item.name] = el)} />
                    </>
                    }
                    <Divider />
                    {
                        data && <Dashboard
                            variables={pannelConfig.variables}
                            serviceName={pannelConfig.servername}
                            pannels={pannelConfig.pannels}
                            datas={data}
                            refreshTask={refreshTask}
                        />

                    }
                    {/* {
                        pannelConfig &&
                        <OfflineImportModal
                            title={
                                intl.formatMessage({
                                    id: 'pages.diagnose.offline_import.title',
                                    defaultMessage: 'Import offline log',
                                })
                            }
                            taskForm={item.extra_params["*"].concat(pannelConfig.taskform)}
                            serviceName={pannelConfig.servicename}
                            queryParams={props?.location?.query}
                            visible={!!item.name && !!offlineImportModalVisible[item.name] ? offlineImportModalVisible[item.name] : false}
                            onVisibleChange={(visible) => {
                                setOfflineImportModalVisible(item.name, visible);
                            }}
                            modalWidth="440px"
                            loading={!!item.name && !!offlineImportLoading[item.name] ? offlineImportLoading[item.name] : false}
                            onFinish={async (value) => {
                                setOfflineImportLoading(item.name, true);
                                let res = await offlineImport({
                                    ...value,
                                    "service_name": pannelConfig.servicename
                                });
                                if (res.code == 200) {
                                    message.success(
                                        intl.formatMessage({
                                            id: 'pages.diagnose.offline_import.success',
                                            defaultMessage: 'Import success',
                                        })
                                    );
                                    refTaskList.current[item.name].reload();
                                } else {
                                    message.error(`${intl.formatMessage({
                                        id: 'pages.diagnose.offline_import.failed',
                                        defaultMessage: 'Import failed',
                                    })}：${res.message}`);
                                }
                                setOfflineImportLoading(item.name, false);
                                setOfflineImportModalVisible(item.name, false);
                                // setOfflineImportModalVisible(false);
                            }}
                        />
                    } */}
                </div>
            )
        }
    })


    return (
        <PageContainer>
            {
                !!multiChannelTaskforms &&
                <Tabs
                    activeKey={currentTab}
                    // tabPosition='left'
                    type='card'
                    items={multiChannelTaskforms}
                    onChange={(key) => {
                        setCurrentTab(key);
                    }}
                />
            }
        </PageContainer>
    );
};

export default Diagnose;
